//
//  InsuranceController.m
//  iCarStyle
//
//  Created by liu nian on 13-9-9.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "InsuranceController.h"
#import "InsuranceDetailController.h"
#import "DataEnvironment.h"
#import "ActionSheetPicker.h"
#import "ALAlertBanner.h"
#import "AppDelegate.h"
#import "MKEnvObserverCenterNetworkStatus.h"
#import "ALAlertBannerManager.h"

@implementation Insurance

@end

@interface InsuranceController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate>{
    BOOL    _isNewCar;
    UIPickerType    _pickerType;
    
}

@property (nonatomic, retain) UIImageView    *headView;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIView    *footerView;;
@property (nonatomic, assign) InsuranceType   type;
@property (nonatomic, retain) NSString        *year;
@property (nonatomic, retain) NSString        *province;
@property (nonatomic, retain) UITextField        *license;//车牌号
@property (nonatomic, retain) UITextField   *priceTF;
@property (nonatomic, retain) NSString      *expireMonth;

@property (nonatomic, retain) NSArray       *companys;
@property (nonatomic, retain) NSMutableArray       *years;
@property (nonatomic, retain) NSArray       *provinces;
@property (nonatomic, retain) NSArray       *months;
@property (nonatomic, retain) UIButton *newCarBtn;
@property (nonatomic, retain) UIButton *provinceBtn;
@end

@implementation InsuranceController

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(inputKeyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(inputKeyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
        self.title = @"车险";
    }
    return self;
}
- (NSString *)tabTitle
{
	return self.title;
}
- (NSString *)tabImageName
{
	return @"image-6";
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    tap.delegate = self;
    tap.numberOfTapsRequired= 1;
    [self.view addGestureRecognizer:tap];
    
    self.companys = [NSArray arrayWithObjects:@"平安保险",@"阳光车险",@"人保车险",@"太平洋车险",@"大地车险", nil];
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cararea" ofType:@"txt"]
                                                    encoding:NSUTF8StringEncoding
                                                       error:NULL];
    self.provinces = [str componentsSeparatedByString:@"\n"];
    
    [self getYears];
    
    self.months = [NSArray arrayWithObjects:@"1月",@"2月",@"3月",@"4月",@"5月",@"6月",@"7月",@"8月",@"9月",@"10月",@"11月",@"12月", nil];
    _type = PINGAN;
    self.year = @"2013年";
    self.province = @"京";
    self.expireMonth = @"1";
}

- (void)getYears{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSDate *date = [NSDate date];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    //int week=0;
    comps = [calendar components:unitFlags fromDate:date];
    int year=[comps year];
    self.years = [NSMutableArray arrayWithCapacity:10];
    for (int i = 0; i< 15; i++) {
        NSString *str = [NSString stringWithFormat:@"%d年",year - i];
        [self.years addObject:str];
    }
    
}

- (void)setType:(InsuranceType)type{
    if (_type !=  type) {
        _type = type;
        [self.tableView reloadData];
    }
}

- (void)setYear:(NSString *)year{
    if (_year != year) {
        _year = year;
        [self.tableView reloadData];
    }
}
- (void) setProvince:(NSString *)province{
    if (_province != province) {
        _province = province;
        [self.tableView reloadData];
    }
}

- (void)setExpireMonth:(NSString *)expireMonth{
    if (_expireMonth != expireMonth) {
        _expireMonth = expireMonth;
        [self.tableView reloadData];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)doSelectedNewCar:(UIButton *)button{
    _isNewCar = !_isNewCar;
    if (_isNewCar) {
        REMOVE_SAFELY(_provinceBtn);
        REMOVE_SAFELY(_license);
        _expireMonth = nil;
        [self.newCarBtn setImage:IMGNAMED(@"bg_checkbox_checked.png") forState:UIControlStateNormal];
        [self.newCarBtn setImage:IMGNAMED(@"bg_checkbox_unchecked.png") forState:UIControlStateHighlighted];
    }else{
        self.expireMonth = @"1";
        [self.newCarBtn setImage:IMGNAMED(@"bg_checkbox_unchecked.png") forState:UIControlStateNormal];
        [self.newCarBtn setImage:IMGNAMED(@"bg_checkbox_checked.png") forState:UIControlStateHighlighted];
    }
    [self.tableView reloadData];
}

#pragma mark 监听键盘的显示与隐藏
-(void)inputKeyboardWillShow:(NSNotification *)notification{
    CGFloat animationTime = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    NSValue *keyboardRectAsObject=[[notification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect;
    [keyboardRectAsObject getValue:&keyboardRect];
    
    [UIView animateWithDuration:animationTime animations:^{
        self.tableView.contentInset=UIEdgeInsetsMake(0, 0,keyboardRect.size.height, 0);
    }];
    
}

-(void)inputKeyboardWillHide:(NSNotification *)notification{
     self.tableView.contentInset=UIEdgeInsetsZero;
}

- (void)handleTap:(UITapGestureRecognizer *)tap{
    self.editing = NO;
    [self.priceTF resignFirstResponder];
    [self.license resignFirstResponder];
}
#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果当前是tableView
        //做自己想做的事
        return NO;
    }
    if ([touch.view isKindOfClass:[UITableViewCell class]] || [touch.view isKindOfClass: [UIButton class]] || [touch.view isKindOfClass: [UITextField class]]){
        return NO;
    }
    return YES;
}
#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return 1;
    }
    if (_isNewCar) {
        return 3;
    }
    return 5;
}

- (NSString *)insuranceType{
    switch (_type) {
        case PINGAN:
            return @"平安保险";
            break;
        case YANGGUANG:
            return @"阳光保险";
            break;
        case RENBAO:
            return @"人保保险";
            break;
        case TAIPINGYANG:
            return @"太平洋保险";
            break;
        case DADI:
            return @"大地保险";
            break;
        default:
            break;
    }
    return @"";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *identifier = @"list";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    }
    
    if (indexPath.section == 1) {
        [cell.textLabel setText:@"开始计算"];
    }else{
    
        switch (indexPath.row) {
            case 0:
            {
                [cell.textLabel setText:@"保险类型:"];
                [cell.detailTextLabel setText:[self insuranceType]];
                [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            }
                break;
            case 1:
            {
                [cell.textLabel setText:@"购车年份:"];
                [cell.detailTextLabel setText:self.year];
                [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            }
                break;
            case 2:
            {
                [cell.textLabel setText:@"购车价格:"];
                [cell.contentView addSubview:self.priceTF];
                
                UILabel *unitLabel = [[UILabel alloc] initWithFrame:CGRectMake(270, 10, 20, 20)];
                [unitLabel setBackgroundColor:[UIColor clearColor]];
                [unitLabel setFont:[UIFont systemFontOfSize:14]];
                [unitLabel setText:@"万"];
                [cell.contentView addSubview:unitLabel];
            }
                break;
            case 3:
            {
                [cell.textLabel setText:@"车牌号码:"];
                [cell.contentView addSubview:self.provinceBtn];
                [cell.contentView addSubview:self.license];
                
            }
                break;
            case 4:
            {
                [cell.textLabel setText:@"保险到期月:"];
                NSString *month = [NSString stringWithFormat:@"%@月",self.expireMonth];
                [cell.detailTextLabel setText:month];
                [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            }
                break;
            default:
                break;
        }
    }

    return cell;
}
- (void)selectProvince{
    _pickerType = Province;
    [self selectProvinceBlock:self.provinceBtn];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}


- (void)showAlertBannerInWindow:(UIButton *)button {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    ALAlertBannerStyle randomStyle = ALAlertBannerStyleWarning;
    ALAlertBannerPosition position = ALAlertBannerPositionUnderNavBar;
    ALAlertBanner *banner = [ALAlertBanner alertBannerForView:appDelegate.window style:randomStyle position:position title:@"错误" subtitle:@"有未填内容" tappedBlock:^(ALAlertBanner *alertBanner) {
        NSLog(@"tapped!");
        [alertBanner hide];
    }];
    banner.secondsToShow = 2;
    banner.showAnimationDuration = 0.25;
    banner.hideAnimationDuration = 0.20;
    [banner show];
}

- (void)toDetailViewController{
    if ([[MKEnvObserverCenterNetworkStatus defaultCenter] getCurrentNetworkStatus] == kNotReachable) {
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        ALAlertBannerStyle randomStyle = ALAlertBannerStyleFailure;
        ALAlertBannerPosition position = ALAlertBannerPositionUnderNavBar;
        ALAlertBanner *banner = [ALAlertBanner alertBannerForView:appDelegate.window style:randomStyle position:position title:@"错误" subtitle:@"网络异常，请检查网络!" tappedBlock:^(ALAlertBanner *alertBanner) {
            NSLog(@"tapped!");
            [alertBanner hide];
        }];
        banner.secondsToShow = 2;
        banner.showAnimationDuration = 0.25;
        banner.hideAnimationDuration = 0.20;
        [banner show];
        return;
    }
    
    
    Insurance *item = nil;
    
    if ([self.priceTF.text length] <= 0) {
        [self showAlertBannerInWindow:nil];
        return;
    }
    
    if (!_isNewCar && [self.license.text length] <= 0) {
        
        return;
    }
    
    item = [[Insurance alloc] init];
    item.isNewCar = YES;
    item.year = self.year;
    item.price = self.priceTF.text;
    item.insuranceType = _type;
    item.expireMonth = self.expireMonth;
    item.license = [NSString stringWithFormat:@"%@%@",self.province,self.license.text];
    
    InsuranceDetailController *detail = [[InsuranceDetailController alloc] initWithInsurance:item];
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)selectCompanyBlock:(id)sender{
    [self handleTap:nil];
    ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
        self.type = selectedIndex;
        [self.tableView reloadData];
    };
    ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
        NSLog(@"Block Picker Canceled");
    };

    [ActionSheetStringPicker showPickerWithTitle:@"选择保险公司" rows:self.companys initialSelection:0 doneBlock:done cancelBlock:cancel origin:sender];
}

- (void)selectYearBlock:(id)sender{
    [self handleTap:nil];
    ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
        self.year = [self.years objectAtIndex:selectedIndex];
        [self.tableView reloadData];
    };
    ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
        NSLog(@"Block Picker Canceled");
    };
    
    [ActionSheetStringPicker showPickerWithTitle:@"选择年份" rows:self.years initialSelection:0 doneBlock:done cancelBlock:cancel origin:sender];
}

- (void)selectMonthBlock:(id)sender{
    [self handleTap:nil];
    ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
        self.expireMonth = [NSString stringWithFormat:@"%d",selectedIndex + 1];
        [self.tableView reloadData];
    };
    ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
        NSLog(@"Block Picker Canceled");
    };
    
    [ActionSheetStringPicker showPickerWithTitle:@"选择月份" rows:self.months initialSelection:0 doneBlock:done cancelBlock:cancel origin:sender];
}

- (void)selectProvinceBlock:(id)sender{
    [self handleTap:nil];
    ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
        NSString *ps = [self.provinces objectAtIndex:selectedIndex];
        NSArray *ss = [ps componentsSeparatedByString:@":"];
        self.province = [ss objectAtIndex:0];
        [self.tableView reloadData];
        [self.provinceBtn setTitle:self.province forState:UIControlStateNormal];
    };
    ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
        NSLog(@"Block Picker Canceled");
    };
    
    [ActionSheetStringPicker showPickerWithTitle:@"选择省份" rows:self.provinces initialSelection:0 doneBlock:done cancelBlock:cancel origin:sender];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        [self toDetailViewController];
        return;
    }
    if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 4) {
        switch (indexPath.row) {
            case 0:{
                _pickerType = Company;
                [self selectCompanyBlock:tableView];
            }
                
                break;
            case 1:{
                 _pickerType = Year;
                [self selectYearBlock:tableView];
            }
               
                break;
            case 4:{
                _pickerType = Month;
                [self selectMonthBlock:tableView];
            }
                
                break;
            default:
                break;
        }
    }

}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == self.priceTF) {
    }
    return YES;
}
//- (void)textFieldDidBeginEditing:(UITextField *)textField{
//    self.showPicker = NO;
//    [textField becomeFirstResponder];
//}
//-(void)textFieldDidEndEditing:(UITextField *)textField{
//    
//}

#pragma mark getter
- (UIImageView *)headView{
    if (!_headView) {
        _headView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 44)];
        [_headView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 10, 100, 20)];
        [textLabel setBackgroundColor:[UIColor clearColor]];
        [textLabel setText:@"车险计算"];
        [textLabel setTextColor:[UIColor darkGrayColor]];
        [_headView addSubview:textLabel];
        
        textLabel.font = FONT_TITLE(22.0f);
        textLabel.textColor = [UIColor flatBlackColor];
        
        
        [self.view addSubview:_headView];
    }
    return _headView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 40)];
        [_footerView addSubview:self.newCarBtn];
        
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 10, 100, 17)];
        [textLabel setBackgroundColor:[UIColor clearColor]];
        [textLabel setText:@"新车未上牌"];
        [textLabel setTextColor:[UIColor darkGrayColor]];
        [_footerView addSubview:textLabel];
        
        textLabel.font = FONT_TITLE(16.0f);
        textLabel.textColor = [UIColor flatBlackColor];
    }
    return _footerView;
}

- (UIButton *)newCarBtn{
    if (!_newCarBtn) {
        _newCarBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, 17, 17)];
        [_newCarBtn setImage:IMGNAMED(@"bg_checkbox_unchecked.png") forState:UIControlStateNormal];
        [_newCarBtn setImage:IMGNAMED(@"bg_checkbox_checked.png") forState:UIControlStateHighlighted];
        [_newCarBtn addTarget:self action:@selector(doSelectedNewCar:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _newCarBtn;
}
- (UIButton *)provinceBtn{
    if (!_provinceBtn) {
        _provinceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_provinceBtn setBackgroundColor:[UIColor flatBlackColor]];
        [_provinceBtn setFrame:CGRectMake(90, 5, 30, 30)];
        [_provinceBtn setTitle:self.province forState:UIControlStateNormal];
        [_provinceBtn addTarget:self action:@selector(selectProvince) forControlEvents:UIControlEventTouchUpInside];
    }
    return _provinceBtn;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds
                                                  style:UITableViewStyleGrouped];
        [_tableView setBackgroundColor:[UIColor whiteColor]];
        [_tableView setBackgroundView:nil];
        [_tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
        [_tableView setShowsVerticalScrollIndicator:NO];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        [_tableView setTableFooterView:self.footerView];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UITextField *)priceTF{
    if (!_priceTF) {
        _priceTF = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 160, 20)];
        [_priceTF setBackgroundColor:[UIColor clearColor]];
        [_priceTF setKeyboardType:UIKeyboardTypeNumberPad];
        [_priceTF setDelegate:self];
        [_priceTF setPlaceholder:@"请输入购车价格"];
    }
    return _priceTF;
}

- (UITextField *)license{
    if (!_license) {
        _license = [[UITextField alloc] initWithFrame:CGRectMake(130, 10, 160, 20)];
        [_license setBackgroundColor:[UIColor clearColor]];
        [_license setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
        [_license setDelegate:self];
        [_license setPlaceholder:@"请输入车牌号"];
    }
    return _license;
}

@end
